<?php

namespace app\common\cachemodel\zl3;

use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zl3FortuneYearActiveAwardRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl3_fortune_year_active_award_record';

    protected $cacheModel = 'active.fortune_year_2022_award';

    /**
     * 添加抽奖记录
     * @param array $data
     * @return bool
     */
    public function SaveData(array $data)
    {
        try
        {
//            $data = [
//                'uid' => '',
//                'cid' => '',
//                'ucid' => '',
//                'active_id' => '',
//                'probability' => '',
//                'create_time' => '',
//            ];

            $this->save($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['active_id'] . ':' . $data['uid'])->rmCache();

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl3FortuneYearActiveAwardRecord model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 获取抽奖记录
     * @param int $uid
     * @param int $activeId
     * @return int
     * @throws \Exception
     */
    public function getAwardNum(int $uid, int $activeId)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $activeId . ':' . $uid)->getDataAndSet(function () use ($activeId, $uid)
        {
            try
            {
                $n = $this->where(['uid' => $uid, 'active_id' => $activeId])->count();

                return ['num' => $n];
            }
            catch (\Exception $e)
            {
                Log::write('Zl3FortuneYearActiveAwardRecord model => getAwardNum()活动获取抽奖次数异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                return [];
            }
        });

        $num = $data ? $data['num'] : 0;
        return (int)$num;
    }
}